//! # Gateway 集成模块
//!
//! 与 rustcloud-gateway 模块的集成，复用其认证提供者

use crate::service::AuthService;
use rustcloud_security::prelude::*;
use std::sync::Arc;

/// Gateway 认证集成
pub struct GatewayAuthIntegration {
    auth_service: Arc<AuthService>,
}

impl GatewayAuthIntegration {
    /// 创建新的 Gateway 集成
    pub fn new(auth_service: Arc<AuthService>) -> Self {
        Self { auth_service }
    }

    /// 从 Gateway 中间件获取认证结果
    pub async fn handle_gateway_auth(
        &self,
        context: &AuthContext,
    ) -> SecurityResult<Option<Principal>> {
        // 使用 AuthService 处理认证
        match self.auth_service.authenticate(context).await {
            Ok(principal) => Ok(Some(principal)),
            Err(SecurityError::AuthenticationFailed { .. }) => Ok(None),
            Err(err) => Err(err),
        }
    }

    /// 集成 Gateway 的授权检查
    pub async fn handle_gateway_authz(
        &self,
        principal: &Principal,
        resource: &Resource,
    ) -> SecurityResult<AuthorizationResult> {
        self.auth_service.authorize(principal, resource).await
    }
}

/// Gateway 中间件适配器
pub struct GatewayMiddlewareAdapter {
    integration: GatewayAuthIntegration,
}

impl GatewayMiddlewareAdapter {
    /// 创建新的适配器
    pub fn new(auth_service: Arc<AuthService>) -> Self {
        Self {
            integration: GatewayAuthIntegration::new(auth_service),
        }
    }

    /// 处理 Gateway 请求
    pub async fn process_request(
        &self,
        context: AuthContext,
        resource: Resource,
    ) -> SecurityResult<AuthorizationResult> {
        // 首先进行认证
        if let Some(principal) = self.integration.handle_gateway_auth(&context).await? {
            // 然后进行授权
            self.integration.handle_gateway_authz(&principal, &resource).await
        } else {
            // 认证失败
            Err(SecurityError::AuthenticationFailed {
                reason: "Authentication required".to_string(),
            })
        }
    }
}